var mongoose = require('mongoose'),
    vpn = require('../models/vpn');

/**
 * 按条件查找, 如果有则更新, 无则插入(包含schema中定义的含有默认值的字段)
 * 注意:
 * 1. 最后的`.exec()`, 按照mongoose官方文档的说法: `.exec()` gives you a fully-fledged promise
 * 2. 使用call绑定上下文为schema
 * @param condition 查询条件
 * @param update 需要更新的document
 * @returns Promise|Array|{index: number, input: string} 包含更新或插入的文档
 */
exports.findOneAndUpdate = function (condition, update, callback) {
  var options =  {"upsert": true, "new": true, setDefaultsOnInsert: true};
  if ('function' === typeof callback) {
    return vpn.findOneAndUpdate
      .call(vpn, condition, update, options, callback).exec();
  } else {
    return vpn.findOneAndUpdate
      .call(vpn, condition, update, options).exec();
  }
};